package cn.tradewin.pmp.pages.master;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.tapestry5.ComponentResources;
import org.apache.tapestry5.Link;
import org.apache.tapestry5.ValueEncoder;
import org.apache.tapestry5.annotations.Environmental;
import org.apache.tapestry5.annotations.Log;
import org.apache.tapestry5.annotations.PageLoaded;
import org.apache.tapestry5.annotations.Property;
import org.apache.tapestry5.beaneditor.BeanModel;
import org.apache.tapestry5.ioc.Messages;
import org.apache.tapestry5.ioc.annotations.Inject;
import org.apache.tapestry5.json.JSONObject;
import org.apache.tapestry5.services.BeanModelSource;
import org.apache.tapestry5.services.javascript.JavaScriptSupport;
import org.codehaus.jackson.JsonGenerationException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;
import org.slf4j.Logger;

import cn.tradewin.pmp.persist.model.MCustomer;
import cn.tradewin.pmp.services.CustomerManageService;

public class CustomerManage {

	@Property
	private final CustomerEncoder customerEncoder = new CustomerEncoder();

	@Property
	private List<MCustomer> customers;

	private MCustomer customer;
	
	@Property
	private MCustomer updCustomer;

	@Property
	private MCustomer addCustomer;

	private boolean inFormSubmission;

	private List<MCustomer> customersSubmitted;

	@Inject
	private CustomerManageService customerService;

	@Inject
	private BeanModelSource beanModelSource;
	
	@Property
	private BeanModel<MCustomer> beanModel;

	@Inject
	private Messages messages;
	
	@Inject
	private ComponentResources resources;
	
	@Environmental
	private JavaScriptSupport js;
	
	@Inject
	Logger log;
	
	@PageLoaded
	void PageLoaded() {
		
	}
	
	@Log
	void onActivate() {
		inFormSubmission = false;
	}

	@Log
	void setupRender() {
		beanModel = beanModelSource.createDisplayModel(MCustomer.class, messages);
		beanModel.add("update", null);
		beanModel.include("selected", "customerNo", "customerName", "customerAddress", "contacterName", "contacterEmal", "contacterTel", "contacterFax", "update");
		beanModel.get("selected").label("");
		beanModel.get("selected").sortable(false);
		beanModel.get("customerNo").sortable(false);
		beanModel.get("customerName").sortable(false);
		beanModel.get("customerAddress").sortable(false);
		beanModel.get("contacterName").sortable(false);
		beanModel.get("contacterEmal").sortable(false);
		beanModel.get("contacterFax").sortable(false);
		beanModel.get("update").label("");
		beanModel.get("update").sortable(false);
	}

	@Log
	void beginRender() {
	}

	@Log
	Object onPassivate() {
		return null;
	}

	@Log
	void onPrepareForRender() {
		if (customers == null) {
			customers = customerService.getAllCustomers();
		}
	}

	@Log
	void onPrepare() {
		if (addCustomer == null) {
			addCustomer = new MCustomer();
		}
		if (updCustomer == null) {
			updCustomer = new MCustomer();
		}
	}

	@Log
	void afterRender() {
		js.require("jquery");
		js.require("bootstrap");
		JSONObject params = new JSONObject();
//		params.put("id", "deptList");
//		params.put("url", this.getPageLink());
//		js.require("DeptManage").invoke("init").with(params);
	}

	public boolean isNoData() {
		if (customers == null || customers.size() == 0)
			return true;
		return false;
	}
	
	@Log
	void cleanupRender() {

	}

	@Log
	void onPrepareForSubmit() {
		inFormSubmission = true;
		customersSubmitted = new ArrayList<MCustomer>();
	}

	/**
	 * delete selected department
	 */
	@Log
	void onSuccessFromListForm() {
		List<String> delCustomers = new ArrayList<String>();
		for (MCustomer m : customersSubmitted) {
			if (m.isSelected()) {
				delCustomers.add(m.getCustomerNo());
			}
		}
		if (delCustomers.size() > 0) {
			customerService.DelCustomers(delCustomers);
		}
	}
	
//	void onSuccessFromUpdForm() {
//		try {
//			updCustomer.setUpdateDatetime(new Date());
////			updDept.setUpdateUser("zhouyc");
//			customerService.updCustomer(updCustomer);
//		} catch (Exception e) {
//			e.printStackTrace();
//		}
//	}

	@Log
	void onSuccessFromAddForm() {
		try {
			customerService.AddCustomer(addCustomer);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	@Log
	JSONObject onUpdateCustomer(String customerNo) {
		ObjectMapper objectMapper = new ObjectMapper();
		updCustomer = customerService.findCustomerByPrimary(customerNo);
		if (updCustomer != null) {
			try {
				return new JSONObject(objectMapper.writeValueAsString(updCustomer));
			} catch (JsonGenerationException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (JsonMappingException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		return null;
	}

	
	private String getPageLink() {
		Link link = resources.createEventLink("updateDept");
		return link.toAbsoluteURI();
	}
	
	public MCustomer getCustomer() {
		return customer;
	}

	public void setCustomer(MCustomer customer) {
		this.customer = customer;
		if (inFormSubmission) {
			this.customersSubmitted.add(customer);
		}
	}
	
	private class CustomerEncoder implements ValueEncoder<MCustomer> {

		public String toClient(MCustomer value) {
			return value.getCustomerNo();
		}

		public MCustomer toValue(String clientValue) {
			MCustomer m = new MCustomer();
			m.setCustomerNo(clientValue);
			return m;
		}
	}
}
